import React, { useEffect, useState } from 'react'
import { Form, Layout, Switch, Tag, Table, Select, Modal, Input, Button, message } from 'antd'
import '../child/ContentStyle.css'
import axios from 'axios'
import moment from 'moment'
import { connect } from 'react-redux'
import { reflushIndex } from '../../../redux/actionCreator/IndexActionCreater'


const { Content } = Layout
const { Option } = Select
function RoleList (props) {
  const { reflushIndex, flush } = props

  let i = 0
  const [myRoleList, setMyRoleList] = useState([])

  //所有的按钮列表
  const [menusList, setMenusList] = useState([])

  //新建角色多选框
  const tagRender = (props) => {

    const { label, closable, onClose } = props

    const onPreventMouseDown = (event) => {
      event.preventDefault()
      event.stopPropagation()
    }

    return (
      <Tag
        color='red'
        onMouseDown={onPreventMouseDown}
        closable={closable}
        onClose={onClose}
        style={{
          marginRight: 3,
        }}
      >
        {label}
      </Tag>
    )
  }

  //修改状态
  const onChange = async (check, record) => {
    await axios({
      url: "http://localhost:8081/roleList/changeRoleStatus",
      method: "post",
      data: {
        flag: check,
        roleName: record.roleName
      },
      headers: {
        'satoken': localStorage.getItem("satoken")
      },
    }).then(r => {
      if (r.data.code === 200) {
        message.success(r.data.msg)
      } else {
        message.error(r.data.msg)
      }
    })
  }

  useEffect(() => {
    axios.get("http://localhost:8081/roleList/getRoleList",
      {
        headers: {
          satoken: localStorage.getItem("satoken")
        }
      }
    ).then(r => {
      if (r.data.code !== 200) {
        return message.error(r.data.msg)
      } else {

        r.data.data.roleList.map((item) => {
          item.key = i++
          item.children.map((t) => {
            t.key = i++
            t.roleName = <Tag color="green">{item.roleName}</Tag>
            return t
          })
          return item
        })
        setMenusList(r.data.data.menus)
        setMyRoleList(r.data.data.roleList)
        return message.success(r.data.msg)
      }
    })
  }, [flush])

  //渲染修改状态列
  const renderSwitch = (data, record) => {
    if (record.roleName !== undefined && record.pstatus === undefined) {
      return <Switch defaultChecked={data === 1 ? true : false} onChange={(check) => onChange(check, record)} />
    } else {
      return <Tag color="magenta">权限状态请至权限列表修改</Tag>
    }
  }

  //提交新建用户的表单
  const onFinish = async (values) => {
    console.log(values)

    await axios({
      url: "http://localhost:8081/roleList/insertNewRole",
      method: "post",
      data: {
        roleName: values.roleName,
        role: values.role
      },
      headers: {
        'satoken': localStorage.getItem("satoken")
      },
    }).then(r => {
      if (r.data.code === 200) {
        message.success(r.data.msg)
        //关闭对话框
        setIsModalVisible(false)
        //强制重新渲染
        reflushIndex(moment().format('MMMM Do YYYY, h:mm:ss a'))
      } else {
        message.error(r.data.msg)
      }
    })

  }


  /***
   * 删除权限
   */
  const deleteRight = async (record) => {
    await axios({
      url: "http://localhost:8081/roleList/deleteRight",
      method: "post",
      data: {
        roleName: record.roleName.props.children,
        rightName: record.pName
      },
      headers: {
        'satoken': localStorage.getItem("satoken")
      },
    }).then(r => {
      if (r.data.code === 200) {
        message.success(r.data.msg)
        reflushIndex(moment().format('MMMM Do YYYY, h:mm:ss a'))
      } else {
        message.error(r.data.msg)
      }
    })
  }

  //修改某个权限
  const handleChange = async (record, optionValue) => {
    await axios({
      url: "http://localhost:8081/roleList/changeRight",
      method: "post",
      data: {
        oldRight: record.pName,
        roleName: record.roleName.props.children,
        rightName: optionValue
      },
      headers: {
        'satoken': localStorage.getItem("satoken")
      },
    }).then(r => {
      if (r.data.code === 200) {
        message.success(r.data.msg)
        reflushIndex(moment().format('MMMM Do YYYY, h:mm:ss a'))
      } else {
        message.error(r.data.msg)
      }
    })

  }

  //渲染菜单列，带选择框
  const renderMenus = (data, record) => {

    if (data === undefined) {
      return <Tag color="blue">前单元格展开</Tag>
    } else {

      return <Select
        defaultValue={record.pName}
        style={{
          width: 130,
        }}
        onChange={(optionValue) => { handleChange(record, optionValue) }}
      >
        {
          menusList.map((item) => {
            //console.log(item, record.pName)
            return <Option key={item} value={item}>{item}</Option>
          })
        }
      </Select >
    }
  }

  //删除角色
  const deleteRole = async (record) => {
    await axios({
      url: "http://localhost:8081/roleList/deleteRole",
      method: "post",
      data: {
        roleName: record.roleName
      },
      headers: {
        'satoken': localStorage.getItem("satoken")
      },
    }).then(r => {
      if (r.data.code === 200) {
        message.success(r.data.msg)
        reflushIndex(moment().format('MMMM Do YYYY, h:mm:ss a'))
      } else {
        message.error(r.data.msg)
      }
    })
  }

  //渲染删除按钮
  const renderDeleteBtn = (data, record) => {
    if (record.rstatus !== undefined) {
      return <Button type="primary" danger onClick={() => { deleteRole(record) }} >删除角色</Button>
    } else {
      return <Button type="dashed" danger onClick={() => { deleteRight(record) }}>删除权限</Button>
    }
  }

  //渲染添加权限按钮
  const addRightBtn = (data, record) => {
    if (record.rstatus !== undefined) {
      return <Button type="primary" >添加权限</Button>
    } else {
      return
    }
  }

  const [isModalVisible, setIsModalVisible] = useState(false)

  //添加权限的对话框按钮
  const [addRightModalVisible, setAddRightModalVisiblee] = useState(false)

  //展示对话框
  const showModal = () => {
    setIsModalVisible(true)
  }

  //ok按钮
  const handleOk = () => {
    setIsModalVisible(false)
  }

  //cancel按钮
  const handleCancel = () => {
    setIsModalVisible(false)
  }

  //表格头，字段
  const columns = [
    {
      title: '角色名',
      dataIndex: 'roleName',
      key: 'roleName',
      align: 'center',
      width: '20%',
    },
    {
      title: '许可菜单(谨慎修改)',
      dataIndex: 'pName',
      key: 'pName',
      align: 'center',
      width: '30%',
      render: (data, record) => renderMenus(data, record)
    },
    {
      title: '状态',
      dataIndex: 'rstatus',
      width: '20%',
      align: 'center',
      key: 'rstatus',
      render: (data, record) => renderSwitch(data, record)
    },
    {
      title: '删除',
      dataIndex: 'delete',
      //width: '30%',
      align: 'center',
      key: 'delete',
      width: '15%',
      render: (data, record) => renderDeleteBtn(data, record)
    },
    {
      title: '添加权限',
      dataIndex: 'add',
      //width: '30%',
      align: 'center',
      key: 'add',
      width: '15%',
      render: (data, record) => addRightBtn(data, record)
    }

  ]

  return (
    <Content className='rolelistContent'>
      {/* 添加用户按钮 */}
      <Button
        type="primary"
        onClick={showModal}
        style={{
          width: 100,
          marginTop: 25,
          marginRight: 20,
          float: 'right',
          marginBottom: 20
        }}>
        添加角色
      </Button>
      {/* 表格 */}
      <Table
        bordered
        columns={columns}
        dataSource={[...myRoleList]}
        defaultExpandAllRows={false}
        pagination={{ pageSize: 7 }}//自定义每页显示的数据条数
      ></Table>

      {/* 创建角色的对话框 */}
      <Modal title="新建角色" visible={isModalVisible} onOk={handleOk} onCancel={handleCancel}>
        <Form
          name="basic"
          labelCol={{
            span: 5,
          }}
          wrapperCol={{
            span: 16,
          }}
          initialValues={{
            remember: true,
          }}
          onFinish={onFinish}
          // onFinishFailed={onFinishFailed}
          autoComplete="off"
        >
          <Form.Item
            label="角色名"
            name="roleName"
            rules={[
              {
                required: true,
                message: '请输入用户名',
              },
            ]}
          >
            <Input placeholder="请勿与之前的角色重名" />
          </Form.Item>

          <Form.Item
            label="权限"
            name="role"
            rules={[
              {
                required: true,
                message: '请选择权限',
              },
            ]}
          >
            <Select
              mode="multiple"
              showArrow
              tagRender={tagRender}
              style={{
                width: '100%',
              }}
              options={menusList.map((item) => {
                return { value: item }
              })}
            />
          </Form.Item>

          <Form.Item
            wrapperCol={{
              offset: 5,
              span: 16,
            }}
          >
            <Button type="primary" htmlType="submit">
              提交
            </Button>
          </Form.Item>
        </Form>
      </Modal>
    </Content>
  )
}

// 获取公共状态
const mapStateToProps = (state) => {
  return {
    flush: state.IndexReducer.reflus
  }
}

// 修改公共状态的方法
const mapDispatchToProps = {
  reflushIndex
}
export default connect(mapStateToProps, mapDispatchToProps)(RoleList)